﻿CROSS_COMPILE 	?= arm-none-eabi-
TARGET		  	?= bare

CC 				:= $(CROSS_COMPILE)gcc
LD				:= $(CROSS_COMPILE)ld
OBJCOPY 	:= $(CROSS_COMPILE)objcopy
OBJDUMP 	:= $(CROSS_COMPILE)objdump

INCDIRS 		:= include/common  \
								include/mcu		\
								include/driver\
								stdio/include
				   			   
SRCDIRS			:= arch/arm_M \
								project \
								driver \
								stdio/lib
#给每个参数添加 -I			   
INCLUDE			:= $(patsubst %, -I %, $(INCDIRS))

#获得每个文件的路径
# $(wildcard pattern)  wildcard 会以 pattern 这个格式，去寻找存在的文件，返回存在文件的名字
SFILES			:= $(foreach dir, $(SRCDIRS), $(wildcard $(dir)/*.S))
CFILES			:= $(foreach dir, $(SRCDIRS), $(wildcard $(dir)/*.c))

#notdir 将路径去掉 只剩文件名
#SFILENDIR = start.S
#CFILENDIR = main.c bsp_beep.c bsp_delay.c bsp_led.c bsp_key.c bsp_gpio.c bsp_clk.c
SFILENDIR		:= $(notdir  $(SFILES))
CFILENDIR		:= $(notdir  $(CFILES))

#$(patsubst pattern,replacement,\$(var))
#patsubst 函数是从 var 变量里面取出每一个值，如果这个符合 pattern 格式，把它替换成 replacement 格式
SOBJS			:= $(patsubst %, obj/%, $(SFILENDIR:.S=.o))
COBJS			:= $(patsubst %, obj/%, $(CFILENDIR:.c=.o))
#所有的 *.o文件
OBJS			:= $(SOBJS) $(COBJS)
VPATH			:= $(SRCDIRS)

.PHONY: clean show_value
	
$(TARGET).bin : $(OBJS)
	$(LD) -Tmap.lds -o $(TARGET).elf $^ 
	$(OBJCOPY) -O binary -S $(TARGET).elf $@ 
	$(OBJCOPY) -O ihex $(TARGET).elf $(TARGET).hex
	$(OBJDUMP) -D -m arm $(TARGET).elf > $(TARGET).dis

$(SOBJS) : obj/%.o : %.S
	$(CC) -Wall -nostdlib -fno-builtin -c -O2  $(INCLUDE) -o $@ $<

$(COBJS) : obj/%.o : %.c
	$(CC) -Wall -march=armv7-m -Wa,-mimplicit-it=thumb -nostdlib -fno-builtin -c -O2  $(INCLUDE) -o $@ $<
img:
	mkimage -n ./tools/imximage.cfg.cfgtmp -T imximage -e 0x87800000 -d $(TARGET).bin $(TARGET).imx
	dd if=/dev/zero of=1k.bin bs=1024 count=1
	cat 1k.bin $(TARGET).imx > $(TARGET).img
show_value:
	@echo INCLUDE=$(INCLUDE)
	@echo SOBJS = ${SOBJS}
	@echo COBJS = ${COBJS}
	@echo CFILES = ${CFILES}
	@echo SFILES = ${SFILES}
	@echo SFILENDIR = $(SFILENDIR)
	@echo CFILENDIR = $(CFILENDIR)
	@echo LIBPATH = $(LIBPATH)

show_section:
	@echo $(shell size $(TARGET).elf)
clean:
	rm -rf $(TARGET).elf $(TARGET).dis $(TARGET).bin $(COBJS) $(SOBJS) $(TARGET).img $(TARGET).imx

	
